#import "HHActivityControler.h"
#import "HHActivityCollectionCell.h"

#import <Masonry/Masonry.h>
#import <BCFoundation/BCFoundation.h>
#import <BCUIKit/BCUIKit.h>
#import <BCPopupScheduler/BCPopupUitl.h>

@interface HHActivityControler ()
<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UIButton *closedBtn;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;

@end

@implementation HHActivityControler
@synthesize alertView = _alertView;

///MARK: - class method
+ (void)showActivies:(NSArray<NSString *> *)imagesUrls complation:(void (^)(NSInteger index) )complation {
    UIViewController *vcRoot = [[[UIApplication sharedApplication] delegate] window].rootViewController;
    HHActivityControler *alertController = [[HHActivityControler alloc] init];
    alertController.imageUrls = imagesUrls;
    alertController.selectedBlock = complation;
    [vcRoot presentViewController:alertController animated:YES completion:NULL];
    
}
+ (instancetype)activityControlerWith:(NSArray<NSString *> *)imagesUrls complation:(void (^)(NSInteger index) )complation {
    HHActivityControler *alertController = [[HHActivityControler alloc] init];
    alertController.imageUrls = imagesUrls;
    alertController.selectedBlock = complation;
    return alertController;
}
///MARK: - system
- (instancetype)init {
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self;
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
  
    [self initializePageSubviews];

}
///MARK: - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageUrls.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HHActivityCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(HHActivityCollectionCell.class) forIndexPath:indexPath];
    cell.imgUrl = [self.imageUrls bc_safeObjectAtIndex:indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self dismissPopupView];
    if (self.selectedBlock) {
        self.selectedBlock(indexPath.item);
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
//    self.alertView.alpha = 0;
    self.alertView.transform = CGAffineTransformMakeScale(0.5, 0.5);
    [UIView animateWithDuration:0.35 animations:^{
//        self.alertView.alpha = 1;
        self.alertView.transform = CGAffineTransformMakeScale(1, 1);
    }];
}
///MARK: - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.imageUrls.count) return;
    _pageControl.currentPage = [self currentIndex];
}

///MARK: - Private method
- (NSInteger)currentIndex
{
    NSInteger index = 0;
    index = (_collectionView.contentOffset.x + self.itemSizeWidth * 0.5) / self.itemSizeWidth;
    
    return MAX(0, index);
}
- (void)scrollToIndex:(NSInteger)targetIndex
{
    if (targetIndex >= self.imageUrls.count) {
        return;
    }
    [self.collectionView setContentOffset:CGPointMake(self.itemSizeWidth*targetIndex, 0) animated:NO];
//    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
///MARK: - Page subviews
- (void)initializePageSubviews {
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    // 整体内容view
    self.alertView = [[UIView alloc] init];
    [self.view addSubview:self.alertView];
    
    [self.alertView addSubview:self.collectionView];
    [self.alertView addSubview:self.pageControl];
    [self.alertView addSubview:self.closedBtn];
    // 单个隐藏pageControl
    self.pageControl.hidden = YES;
//    self.pageControl.hidden = self.activites.count<2;
    
    // Constraints
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        make.width.mas_equalTo(self.itemSizeWidth);
        make.height.mas_equalTo(405+40+50);
    }];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.alertView);
        make.height.mas_equalTo(405);
    }];
    [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.collectionView.mas_bottom).offset(1);
        make.centerX.mas_equalTo(self.collectionView);
    }];
    [_closedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.alertView);
        make.centerX.mas_equalTo(self.alertView);
        make.size.mas_equalTo(CGSizeMake(55, 55));
    }];
    
}
///MARK: - getter
- (UIButton *)closedBtn {
    if (!_closedBtn) {
        @BCWeakify(self);
        _closedBtn = [UIButton bc_allocButton:^(UIButton * _Nonnull btn) {
            [btn setImage:[UIImage imageNamed:@"home_floatLayer_close_icon"] forState:UIControlStateNormal];
        } action:^(UIButton * _Nonnull btn) {
            @BCStrongify(self);
            [self dismissPopupView];
        }];
    }
    return _closedBtn;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake(self.itemSizeWidth, 405);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.scrollsToTop = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
//        _collectionView.bounces = NO;
        // 业务需求禁止滚动
        _collectionView.scrollEnabled = NO;
        [_collectionView registerClass:[HHActivityCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass(HHActivityCollectionCell.class)];
    }
    return _collectionView;
}
- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.numberOfPages = self.imageUrls.count;
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:0.8 alpha:0.6];
        _pageControl.userInteractionEnabled = NO;
    }
    return _pageControl;
}
- (CGFloat)itemSizeWidth {
    return ceil(kBCSCREEN_WIDTH-(MAX(46, kBCSCREEN_PhoneWidthRatio*46)));
}

///MARK: - UIViewControllerAnimatedTransitioning
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[HHAlertControllerAnimated alloc]init];
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[HHAlertControllerAnimated alloc]init];
    
}

///MARK: -BCPopupView
- (void)showPopupView {
    UIViewController *vcRoot = [[[UIApplication sharedApplication] delegate] window].rootViewController;
    [vcRoot presentViewController:self animated:YES completion:NULL];
}
- (void)dismissPopupView {
    //    NSInteger currentIndex = [self currentIndex];
    //    NSInteger targetIndex = currentIndex + 1;
    //
    //    if (targetIndex >= self.imageUrls.count) {
    //        [self dismissViewControllerAnimated:NO completion:NULL];
    //    }else{
    //        [self scrollToIndex:targetIndex];
    //    }
        [self dismissViewControllerAnimated:NO completion:NULL];
}
- (BOOL)canRegisterFirstPopupViewResponder{
    BOOL touch = [[BCPopupUitl findCurrentViewController] isKindOfClass:NSClassFromString(@"QLKNewHomeViewController")];
    return touch;
}

- (BCPopupViewUntriggeredBehavior)popupViewUntriggeredBehavior{
    return BCPopupViewUntriggeredBehaviorAwait;
}
@end
